package com.haina.vote.controller;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.github.pagehelper.PageInfo;
import com.haina.vote.entity.KqFwModel;
import com.haina.vote.entity.KqFwPerformance;
import com.haina.vote.enums.TaskStatusEnum;
import com.haina.vote.service.IKqFwService;
import com.haina.vote.utils.RandomCodeUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.util.*;


@Controller
@RequestMapping("/api")
@ResponseBody
public class ApiController {
    @Autowired
    private IKqFwService kqFwService;
    //获取编号接口
    @GetMapping(value = "/getNumber")
    @ResponseBody
    public KqFwModel addUI(){
        KqFwModel resModel=new KqFwModel();
//        resModel.setNumber(newNumberStr);
        System.out.println(resModel);
        return resModel;
    }

    @RequestMapping(value = "/findTaskApi")
    @ResponseBody
    public Map<String,Object> findTaskUI(@RequestParam(name = "page",required = true,defaultValue = "1")Integer page,@RequestParam(name = "pageSize",required = true,defaultValue = "10")Integer pageSize,@RequestParam(name = "TL")String TL){
        List<KqFwModel> kqFwModelList=kqFwService.findTask(page,pageSize);
        PageInfo pageInfo=new PageInfo(kqFwModelList);
        Map<String,Object> map = new HashMap<>();
        map.put("data",pageInfo);
        return map;
    }

    //新增任务单接口
    @PostMapping("/createTask")
    @ResponseBody
    public Map<String,Object> addTask(KqFwModel kqFwModel) throws JsonProcessingException {
        //首先获取科情服务任务单主要信息并添加到数据库
        //设置状态
        kqFwModel.setStatus(TaskStatusEnum.SUBMIT.getCode());
        kqFwModel.setCreate_time(new Date());
        //生成六位数的随机码 并返回到页面
        String code=RandomCodeUtils.RandomCode();
        kqFwModel.setCode(code);
        //生成编号1、首先查询数据库当前最大编号 2、处理编号
        KqFwModel taskMaxTime = kqFwService.findTaskMaxTime();
        //调用编号生成方法
        String newNumber = RandomCodeUtils.number(taskMaxTime);
        kqFwModel.setNumber(newNumber);
        Integer id=kqFwService.addTask(kqFwModel);
        //存储返回的数据
        Map<String,Object> resmap = new HashMap<>();

        if (id!=null&&id!=-1){
           resmap.put("status","success");
           resmap.put("code",code);

           return resmap;

        }else {
            resmap.put("status","error");

            return resmap;
        }
    }
    //修改任务单接口
    @PostMapping("/updateTask")
    @ResponseBody
    public String updateTask(KqFwModel kqFwModel){
        //修改完成后状态回到待审核或已提交状态
        kqFwModel.setStatus(TaskStatusEnum.SUBMIT.getCode());
        kqFwModel.setUpdate_time(new Date());
        kqFwService.updateTask(kqFwModel);
        if (kqFwModel.getId()!=null&&kqFwModel.getId()!=-1){
            return "OK";
        }else {
            return "FALL";
        }
    }
    //提交反馈
    //修改任务单接口
    @PostMapping("/updatefeedback")
    @ResponseBody
    public String updatefeedback(KqFwModel kqFwModel){
        kqFwModel.setUpdate_time(new Date());
        int rows= kqFwService.updatefeedback(kqFwModel);
        if (rows>0){
            return "OK";
        }else {
            return "FALL";
        }
    }

    //删除科情服务任务单
    @GetMapping("/deleteTask")
    @ResponseBody
    public String deleteTask(@RequestParam(name = "id")Integer id){
        int row = kqFwService.deleteTask(id);
        if (row>0){
            return "success";
        }else {
            return "error";
        }

    }
    //查找id是否存在
    @GetMapping("/findIsExist")
    public Map<String,Object> findIsExist(@RequestParam(name = "id")Integer id){
        Map<String,Object> deletePerformanceInfo= new HashMap<>();

        int rows = kqFwService.findIsExist(id);
        if (rows>0){
            deletePerformanceInfo.put("code",200);
            deletePerformanceInfo.put("success",true);
            deletePerformanceInfo.put("message","存在");
            return deletePerformanceInfo;
        }else {
            deletePerformanceInfo.put("success",false);
            deletePerformanceInfo.put("message","不存在");
            return deletePerformanceInfo;
        }

    }
    //删除子表内容
    @GetMapping("/deletePerformanceById")
    public Map<String,Object> deletePerformanceById(@RequestParam(name = "id")Integer id){
       Map<String,Object> deletePerformanceInfo= new HashMap<>();
       //首先根据id判断是否存在此条数据
       int rows = kqFwService.findIsExist(id);
       if (rows>0){
           int del_Rows=kqFwService.deletePerformanceById(id);
           if (del_Rows>0){
               deletePerformanceInfo.put("code",1);
               deletePerformanceInfo.put("message","数据库删除成功");
               return deletePerformanceInfo;
           }else {
               deletePerformanceInfo.put("code",500);
               deletePerformanceInfo.put("message","数据库删除异常");
               return deletePerformanceInfo;
           }
       }else {
           deletePerformanceInfo.put("code",2);
           deletePerformanceInfo.put("message","数据库不存在，直接删除");
           return deletePerformanceInfo;
       }

    }
    //根据id查询信息接口
    //查询需要修改的信息并回显
    @RequestMapping("/getTaskById")
    @ResponseBody
    public KqFwModel updateTaskUI(Integer id){
        KqFwModel kqFwModel = kqFwService.findTaskById(id);
        return kqFwModel;
    }
    //根据处理参数修改任务单的状态
    @GetMapping("/setStatus")
    @ResponseBody
    public Map<String,Object> setStatus(@RequestParam(name = "id") Integer id,@RequestParam(name = "status") Integer status){
        //如果进行完成操作，需要先验证反馈资料的下载地址是否存在
        int rows = kqFwService.setStatus(id,status);
        Map<String,Object> map = new HashMap<>();
        Map<String,Object> data = new HashMap<>();
        if (rows>0){
            map.put("success",true);
            map.put("message","操作成功");
            data.put("id",id);
            data.put("type",status);
            map.put("data",data);
            return map;
        }else {
            map.put("success",false);
            map.put("message","操作失败");
            data.put("id",id);
            data.put("type",status);
            map.put("data",data);
            return map;
        }
    }
    @PostMapping("/reject")
    @ResponseBody
    public Map<String,Object> reject(@RequestParam(name = "reject_taskId") Integer reject_taskId,@RequestParam(name = "reject_taskStatus") Integer reject_taskStatus,@RequestParam("reject_Info")String reject_Info){
        int rows = kqFwService.reject(reject_taskId,reject_taskStatus,reject_Info);
        Map<String,Object> map = new HashMap<>();
        Map<String,Object> data = new HashMap<>();
        if (rows>0){
            map.put("success",true);
            map.put("message","操作成功");
            data.put("id",reject_taskId);
            data.put("type",reject_taskStatus);
            data.put("info",reject_Info);
            map.put("data",data);
            return map;
        }else {
            map.put("success",false);
            map.put("message","操作失败");
            data.put("id",reject_taskId);
            data.put("type",reject_taskStatus);
            data.put("info",reject_Info);
            map.put("data",data);
            return map;
        }
    }
    //根据id获取到文件下载地址并进行下载
    @PostMapping("/downloadMeansById")
    @ResponseBody
    public Map<String,Object> downloadMeans(Integer id){
       KqFwModel kqFwModel = kqFwService.downloadMeans(id);
        //存储返回的数据
        Map<String,Object> map = new HashMap<>();
       if(kqFwModel.getMeans_url()!=null && !kqFwModel.getMeans_url().trim().equals("")){
            map.put("message","success");
            map.put("data",kqFwModel.getMeans_url());
            return map;
       }else {
           map.put("message","error");
           map.put("data","");
           return map;
       }
    }
    //验证随机码是否一致
    @PostMapping("/checkCode")
    @ResponseBody
    public Map<String,Object> checkCodeById(Integer id,String code,String reqtype){
      KqFwModel kqFwModel = kqFwService.findTaskById(id);
      Map<String,Object> map=new HashMap<>();
      //查询到的目标code
      String target_code=kqFwModel.getCode();
      if (code.equals(target_code)){
          map.put("checkResult",true);
          map.put("reqtype",reqtype);
          map.put("data",kqFwModel);
          return map;
      }else {
          map.put("checkResult",false);
          map.put("reqtype",reqtype);
          return map;
      }
    }
    //上传反馈资料
    //创建选项
    @RequestMapping("/uploadMeans")
    @ResponseBody
    public Map<String,Object> saveMeans(HttpServletRequest request, MultipartFile upload, @RequestParam(name = "id")Integer id) throws Exception {
        //使用fileupload组件完成文件上传
        //上传位置
        String path =request.getSession().getServletContext().getRealPath("/uploads/kqfw");
        Map<String,Object> map=new HashMap<>();
        String filename=null;
        //判断路径是否存在
        File file=new File(path);
        if (!file.exists()){
            file.mkdirs();
        }
        filename = upload.getOriginalFilename();
        //String uuid = UUID.randomUUID().toString().replace("-","");
        filename=filename;
        //完成文件上传
        upload.transferTo(new File(path,filename));
        String fileurl="/uploads/kqfw/"+filename;
        KqFwModel param =new KqFwModel();
        param.setMeans_url(fileurl);
        param.setId(id);
        //反馈资料上传成功后设置状态为4 资料查找完成！
        param.setStatus(4);
        int rows = kqFwService.updateMeansUrl(param);
        if (rows>0){
            map.put("success",true);
            map.put("message","上传反馈资料成功！");
            map.put("data",param);
            return map;
        }else {
            map.put("success",false);
            map.put("message","上传反馈资料失败！");
            map.put("data","");
            return map;
        }
    }
}
